package com.cloud.site.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cloud.platform.IDao;
import com.cloud.platform.util.Constants;
import com.cloud.platform.util.StringUtil;
import com.cloud.site.model.Catagory;
import com.cloud.site.model.Site;
import com.cloud.site.vo.SiteVo;

@Component
public class SiteService {

	@Autowired
	private IDao dao;
	
	public List<SiteVo> searchSites(String userId) {
		if(StringUtil.isNullOrEmpty(userId)) {
			return new ArrayList();
		}
		
		// search all catagorys
		List<Catagory> catagorys = searchCatagorys(userId);
		
		// search all sites
		List<Site> sites = dao.getAllByHql("from Site where uid = ? order by sn,createTime", userId);
		
		// combine sites may by catagory
		Map<String, List> siteMap = new HashMap();
		String cId = null;
		
		for(Site s : sites) {
			cId = s.getCatagoryId();
			
			if(StringUtil.isNullOrEmpty(cId)) {
				continue;
			}
			
			if(!siteMap.containsKey(cId)) {
				siteMap.put(cId, new ArrayList());
			}
			
			siteMap.get(cId).add(s);
		}
		
		// combine site vo
		List<SiteVo> result = new ArrayList();
		SiteVo vo = null;
		
		for(Catagory c : catagorys) {
			vo = new SiteVo();
			
			// add every catagory
			vo.setCatagory(c);
			
			// add catagory sites
			vo.setSites(siteMap.get(c.getId()));
			
			result.add(vo);
		}
		
		return result;
	}
	
	public List<Catagory> searchCatagorys(String userId) {
		if(StringUtil.isNullOrEmpty(userId)) {
			return new ArrayList();
		}
		
		return dao.getAllByHql("from Catagory where uid = ? order by sn,createTime", userId);
	}
	
	public void saveCatagory(Catagory catagory, String userId) {
		if(catagory == null || StringUtil.isNullOrEmpty(userId)) {
			return;
		}
		
		if(StringUtil.isNullOrEmpty(catagory.getId())) {
			catagory.setId(Constants.getID());
			catagory.setUid(userId);
			catagory.setCreateTime(new Date());
		}
		
		dao.saveObject(catagory);
	}
	
	public void saveSite(Site site, String userId) {
		if(site == null || StringUtil.isNullOrEmpty(userId)) {
			return;
		}
		
		if(StringUtil.isNullOrEmpty(site.getId())) {
			site.setId(Constants.getID());
			site.setUid(userId);
			site.setCreateTime(new Date());
		}
		
		dao.saveObject(site);
	}
	
	public Catagory getCatagory(String catagoryId) {
		if(StringUtil.isNullOrEmpty(catagoryId)) {
			return new Catagory();
		}
		
		return (Catagory) dao.getObject(Catagory.class, catagoryId);
	}
	
	public Site getSite(String siteId) {
		if(StringUtil.isNullOrEmpty(siteId)) {
			return new Site();
		}
		
		return (Site) dao.getObject(Site.class, siteId);
	}
}
